<template>
  <el-dialog
    v-model="visible"
    title="选择商品规格"
    width="1160"
    align-center
    :show-close="true"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="clickClose"
  >
    <div class="products-detail">
      <header>
        <div class="left">
          <img :src="optionInfo.detail.mainPicUrl" alt="" />
        </div>
        <div class="right">
          <p class="name f18">{{ optionInfo.detail.productName || "暂无sku信息" }}</p>
          <b class="price f14"><span>采购价：</span>¥{{ skuObj?.clinetRealPrice || "--" }}</b>
          <p class="f12 total">库存：{{ skuObj?.factoryStock || "暂无sku信息" }}</p>
          <p class="unit f12">单位：{{ getName(skuObj?.productUnit) || "暂无sku信息" }}</p>
        </div>
      </header>
      <div class="block"></div>
      <!-- 动态规格 -->
      <div class="specificate-box" v-for="(item, i) in _detail.specificationList" :key="i">
        <div class="specificate-name f18 mb10">{{ item.specificationName }}</div>
        <div class="specificate-bo">
          <div
            class="specificate-b"
            :class="{
              'disabled-wrap': itema.disable === 1,
              active: _detail.specificationList[i].showItem == b
            }"
            v-for="(itema, b) in item.children"
            :key="b"
          >
            <!--         sku   -->
            <div
              class="spe-box"
              :class="{ active: _detail.specificationList[i].showItem == b }"
              @click="addSku(item, itema, i, b, true, itema.isActive)"
            >
              <img
                class="mr10"
                v-if="itema.statsText && item.speType === specType.IMAGE_TYPE"
                :src="itema.statsText"
                alt=""
                width="24"
                height="24"
                style="border-radius: 4px"
              />

              <div
                v-if="itema.statsText && item.speType === specType.COLOR_TYPE"
                class="spe-box-img mr10"
                :style="{ 'background-color': itema.statsText }"
              ></div>
              <span>{{ itema.propTemplateVal || itema.specificationVal }}</span>
            </div>
            <!--         颜色   -->
            <!-- <div
              class="spe-box-img"
              :class="{ active: _detail.specificationList[i].showItem == b }"
              :style="{ 'background-color': itema.statsText }"
              v-if="item.speType === specType.COLOR_TYPE"
            >
              <div class="mask">
                <el-tooltip :content="itema.specificationVal" placement="bottom" effect="light">{{
                  itema.specificationVal
                }}</el-tooltip>
              </div>
            </div> -->
            <!--          图片  -->
            <!-- <div
              class="spe-box-img"
              :class="{ active: _detail.specificationList[i].showItem == b }"
              v-if="item.speType === specType.IMAGE_TYPE"
            >
              <img :src="itema.statsText" alt="" />
              <div class="mask">
                <el-tooltip :content="itema.specificationVal" placement="bottom" effect="light">{{
                  itema.specificationVal
                }}</el-tooltip>
              </div>
            </div> -->
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" plain @click="clickClose">取消</el-button>
        <el-button type="primary" :disabled="!skuObj" @click="submit">添加到入库单</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, onMounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import { getObjKeys, getArrayCombine, _throttle } from "@/utils";
import { saveTempProduct } from "@/apis/procure/entry";
import { useRoute } from "vue-router";
import useCodeArrStore from "@/store/modules/select";
const route = useRoute();
import { selectSpe } from "@/apis/shopHome/detail";

const visible = ref(false);
const _detail = ref({}); //商品详情
const skuObjData = ref({}); // 数据集
const keys = ref([]); // 属性集
// 1文字 2颜色  3图片
const SkuLists = reactive({
  SkuList: []
});
/**
 * 规格展示类型
 */
const specType = {
  TEXT_TYPE: 1,
  COLOR_TYPE: 2,
  IMAGE_TYPE: 3
};
const emit = defineEmits(["close"]);
const props = defineProps({
  optionInfo: {
    type: Object,
    default: () => {
      return {
        isShow: false,
        detail: {}
      };
    }
  }
});
watch(
  () => props.optionInfo.isShow,
  async val => {
    visible.value = val;
  },
  { deep: true }
);
watch(
  () => props.optionInfo.detail,
  async val => {
    // _detail.value = val;
    console.log("这是商品详情", val);
    const _newVal = JSON.parse(JSON.stringify(val));

    getSkuObj(_newVal);

    _newVal.specificationList.forEach(item => {
      item.showItem = null;
      item.children?.map((_item, _index) => {
        _item.isActive = false;
      });
    });
    _detail.value = _newVal;
    _detail.value._specificationList = val.specificationList;

    nextTick(() => {
      _detail.value.specificationList.forEach((item, index) => {
        item.children?.map((_item, _index) => {
          if (_item.initSelect === 1) {
            addSku(item, _item, index, _index, false, _item.isActive, false);
          }
        });
      });

      // 请求接口获取置灰sku
      let activeArr = [];
      _detail.value.specificationList?.map(obj => {
        obj?.children?.map(_obj => {
          if (_obj.isActive) {
            activeArr.push({ ..._obj, specificationName: obj.specificationName });
          }
        });
      });
      selectSpeFun(activeArr);
    });
  },
  { deep: true }
);

const getName = code => {
  return useCodeArrStore().getDictName("shop_unit", code);
};

const submit = () => {
  saveTempProduct({
    skuId: skuObj.value.skuId,
    code: route.query._time
  }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "暂存成功",
        type: "success"
      });
      clickClose();
    }
  });
};

const getSkuObj = data => {
  let skuObj = {};
  data.skuList?.forEach(item => {
    const properties = JSON.parse(item.properties) || [];
    const field = properties.reduce((pre, cur) => {
      return pre ? `${pre};${cur.specificationVal}` : `${pre}${cur.specificationVal}`;
    }, "");
    skuObj[field] = { ...item };
  });
  keys.value = data.specificationList.map(item => {
    return {
      specificationName: item.specificationName,
      item: item.children.map(item => item.specificationVal)
    };
  });
  skuObjData.value = initSKU(skuObj);
};
const initSKU = sku => {
  let resultSKU = [];
  let skuKeys = getObjKeys(sku);
  for (let i in skuKeys) {
    let skuKey = skuKeys[i]; // 获取一条SKU的key
    let skuData = sku[skuKey]; // 获取一条SKU的相关数据
    let skuKeyAttrs = skuKey.split(";"); // 获取SKU的key的属性数组
    let combArr = getArrayCombine(skuKeyAttrs);

    resultSKU[skuKey] = {
      count: skuData.count,
      prices: [skuData]
    };
    // for (let j = 0; j < combArr.length; j++) {
    //   let key = combArr[j].join(";");
    //   if (resultSKU[key]) {
    //     resultSKU[key].count += skuData.count;
    //     resultSKU[key].prices.push(skuData.price);
    //   } else {
    //     resultSKU[key] = {
    //       count: skuData.count,
    //       prices: [skuData]
    //     };
    //   }
    // }
  }
  return resultSKU;
};

const skuObj = ref({}); //点击之后 查找出来的sku对象
const addSku = _throttle((item, itema, a, b, getRemark, isActive, selectSpe = true) => {
  let skuItemFieldArr = [],
    skuItemField = "";
  SkuLists.SkuList = [];
  item.children?.map(obj => {
    obj.isActive = false;
  });
  itema.isActive = !isActive;
  _detail.value.specificationList[a].showItem = null;
  if (itema.isActive) {
    _detail.value.specificationList[a].showItem = b;

    _detail.value.specificationList.forEach(items => {
      skuItemFieldArr.push(items.children[items.showItem]?.specificationVal);
      SkuLists.SkuList.push(items.children[items.showItem]?.productSpecificationId);
    });
    skuItemField = skuItemFieldArr?.join(";") || "";
  }

  skuObj.value = skuObjData.value[skuItemField]?.prices[0];

  console.log("选中的sku===", skuObj.value);

  // 请求接口获取置灰sku
  let activeArr = [];
  _detail.value.specificationList?.map(obj => {
    obj?.children?.map(_obj => {
      if (_obj.isActive) {
        activeArr.push({ ..._obj, specificationName: obj.specificationName });
      }
    });
  });
  selectSpe && selectSpeFun(activeArr);
}, 0);

//查询置灰的sku规格数据
const selectSpeFun = activeArr => {
  const activeIds = activeArr?.map(item => item.specificationValId); //选中的规格ids
  const selectValArr = activeArr?.map(item => {
    return {
      specificationName: item.specificationName,
      selectVal: item.specificationVal
    };
  }); //选中的规格ids
  selectSpe({
    specificationList: _detail.value?._specificationList,
    skuList: _detail.value?.skuList,
    selectSpeList: selectValArr
  }).then(res => {
    if (res.code === 200) {
      //返回的带有disabled的规格数据
      let childArr = [];
      res.data.specificationList?.map(item => {
        childArr = [...childArr, ...item.children];
      });

      _detail.value?.specificationList?.map(item => {
        item?.children?.map(_item => {
          const currObj = childArr?.find(
            o => o.specificationValId + "=" + o.specificationVal === _item.specificationValId + "=" + _item.specificationVal
          );
          _item.disable = currObj.disable;
        });
      });
      console.log("处理后的规格===", _detail.value?.specificationList);
    }
  });
};

onMounted(async () => {});

const clickClose = () => {
  emit("close");
};
</script>

<style lang="scss" scoped>
.block {
  height: 10px;
  margin: 20px -24px;
  background-color: #eef1f4;
}
.products-detail {
  header {
    display: flex;
    .left {
      img {
        width: 150px;
        height: 150px;
        border-radius: 4px;
      }
    }
    .right {
      flex: 1;
      padding-left: 20px;
      color: #3d3d3d;
      .price {
        display: inline-block;
        margin: 16px 0 10px 0;
        span {
          color: #ff3333;
        }
      }
      .total {
        margin-bottom: 10px;
      }
      .unit {
        color: #86909c;
      }
    }
  }
}
.specificate-box {
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;

  .specificate-bo {
    display: flex;
    flex-wrap: wrap;

    .specificate-b {
      display: flex;
      flex-wrap: wrap;

      .spe-box {
        display: flex;
        margin-bottom: 10px;
        align-items: center;
        cursor: pointer;
        justify-content: center;
        border-radius: 3px;
        border: 1px solid #dcdfe6;
        font-weight: 400;
        font-size: 14px;
        color: #606266;
        margin-right: 20px;
        padding: 5px 10px;
        line-height: 24px;
        text-align: left;
        font-style: normal;
        text-transform: none;

        &.active {
          border: 1px solid #ff8928;
        }
      }

      &.disabled-wrap {
        cursor: not-allowed;
        .spe-box {
          pointer-events: none;
          background-color: #f9f9f9;
          color: gray;
        }
      }

      .spe-box-img {
        width: 24px;
        height: 24px;
        position: relative;

        cursor: pointer;
        border-radius: 4px;
        border: 1px solid transparent;

        &.active {
          border: 1px solid #ff8928;
        }

        img {
          width: 100%;
          height: 100%;
        }

        .mask {
          display: flex;
          align-items: center;
          justify-content: center;
          position: absolute;
          bottom: 0;
          width: 90px;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          /* 解决纯字母溢出隐藏失效*/
          word-break: break-all;
          font-weight: 400;
          font-size: 14px;
          color: #ffffff;
          line-height: 24px;
          height: 24px;
          text-align: center;
          background: linear-gradient(180deg, rgba(26, 26, 26, 0.16) 0%, #1a1a1a 100%);
          border-radius: 0;

          :deep(.el-only-child__content.el-tooltip__trigger.el-tooltip__trigger) {
            display: inline-block;
            width: 100%;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            line-height: 24px;
            height: 24px;
          }
        }
      }
    }
  }
}
</style>
